let fs = require('fs');
let express = require('express');
let app = express();
let request = require('request');
let cheerio = require('cheerio');

let champions = require('./data/champion');

let output_dir = './output-data/'
console.log('nodejs champions number:'+Object.keys(champions).length);

console.log('hello nodejs');

let link = 'http://ossweb-img.qq.com/images/lol/img/champion/';

let download = function(uri,filename,callback){
	request.head(uri,function(err,res,body){
		request(uri).pipe(fs.createWriteStream(filename)).on('close',callback);
	});
};

let retHtml = '<html><head></head><body><div>';
let endHtml = '</div></body><html>';


for(let key in champions){
	if(champions.hasOwnProperty(key)){
		console.log(key + '->'+champions[key]);
		let img = '<img src="'+link+champions[key]+'.png">';
		retHtml+= img;
		download(link+champions[key]+'.png',output_dir+champions[key]+'.png',function(){
			//do nothing.
		});
	}
}

retHtml += endHtml;



app.get('/',function(req,res){
	let username = '';
	res.send(retHtml);
	// request('http://lol.qq.com/web201310/info-heros.shtml',function(error,response,body){
	// 	if(!error&&response.statusCode == 200){
	// 		$ = cheerio.load(body);
	// 		console.log('hello misan');
	// 		console.log($('#jSearchHeroDiv').children().length);
	// 		//for(let ix = 0;ix < heroname.length;ix++){
	// 		//	let name = heroname[ix].text();
	// 		//	console.log('hero name:'+name);
	// 		//}
	// 		username = 'hero';
	// 		res.send($('#jSearchHeroDiv').html());
	// 	}
	// 	else{
	// 		username = 'world';
	// 		console.log('no user name get!');
	// 		res.send('hello '+username);
	// 	}
	// 	console.log('mi hello '+username);
	// });
});
let server = app.listen(3000,function(){
	console.log('server start on port %d',server.address().port);
});
